@extends("layouts.backend.webadmin")
@section('page-header')
<h1>
    <small>access\user</small>
</h1>
@endsection

@section('content')
<link rel="stylesheet" href="{{env('APP_ROOT')}}/assets/select2/css/select2.min.css">
<link rel="stylesheet" href="{{env('APP_ROOT')}}/assets/select2/css/select2totree.css">
<!-- Main content -->
<section class="content">
    <div class="row">
        <div class="col-xs-12">

            <div class="box">
                <!--<div class="box-header">
                    <h3 class="box-title">用户列表</h3>
                </div>-->
                <!-- /.box-header -->
                <div class="box-body">
                    <table id="example1" class="table table-bordered table-striped">
                        <thead>
                        <tr>

                        </tr>
                        </thead>

                        <tbody>
                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<form id="add-form">
    <div id="edit" style="display: none;" class="box box-success">

        <div class="box-body">
            <input type="hidden" name="id">
            <label for="name">用户名</label>
            <input name="name" class="form-control" type="text" placeholder="用户名" readonly>
            <br>
            <label for="real_name">真实姓名</label>
            <input name="real_name" class="form-control" type="text" placeholder="真实姓名">
            <br>
            <label for="email">邮箱</label>
            <input name="email" class="form-control" type="text" placeholder="邮箱">
            <br>
            <label for="phone">手机</label>
            <input name="phone" class="form-control" type="text" placeholder="手机">
            <br>
            <!--user roles-->
            <label for="phone">角色</label>
            <div id="roles"></div><br>
            <!--user ogzs-->
            <div class="form-group">
                <label for="parent-ogz">机构</label><br/>
                <select class="form-control" id="parent-ogz" name="ogz_id" style="width: 100%">
                </select>
            </div>
            <div class="box-footer">
                <button id="submit-data" type="button" class="btn btn-primary">确定</button>
            </div>
        </div>
        <!-- /.box-body -->
    </div>
</form>
<!--验证绑定用户信息-->
<form id="relation_form">
<div id="relation" style="display: none;" class="box box-success">
    <div class="box-body">
        <label for="relation_name">用户名</label>
        <input name="relation_name" class="form-control" type="text" placeholder="用户名">
        <br>
        <label for="relation_password">密码</label>
        <input name="relation_password" class="form-control" type="password" placeholder="密码">

        <div class="box-footer">
            <button type="button" class="btn btn-primary user-relation">确定</button>
        </div>
    </div>
    <!-- /.box-body -->
</div>
</form>
<!--基础信息-->
<div class="user-base" style="display: none;"></div>
<!--收货地址-->
<div class="user-address" style="display: none;"></div>
@stop
@section('javascript-end')
<script src="{{env('APP_ROOT')}}/assets/layui/layui.all.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/select2.min.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/select2totree.js"></script>
<script src="{{env('APP_ROOT')}}/assets/select2/js/i18n/zh-CN.js"></script>
<script src="{{env('APP_ROOT')}}/js/common.js"></script>
<script>
    $(function () {
        var m1 = manage();
        var tables = $('#example1').DataTable({
            //调整结构
            'dom': '<"dataTables_filter">rtip',
            'oLanguage'   :{
                'sUrl'    : '{{env("APP_ROOT")}}/assets/bootstrap/js/zh_cn.json'
            },
            "bSort": false,
            "processing": true,
            "autoWidth":true,
            //开启服务器模式
            serverSide: true,
            ajax: {
                //指定数据源
                url: "{{route('admin.access.user.search')}}",
                type: "GET",
                data: function(d){
                    delete d.columns;
                    return d;
                },
                //接受服务器数据
                dataSrc:function(json){
                    getToken();
                    return json.data;
                }
            },
            //每页显示三条数据
            pageLength: {{$pageNum}},
            //data值对应数据库字段名
            columns: [
                {
                    'title':'用户名',
                    "data": "name"
                },
                {
                    'title':'真实姓名',
                    "data": "real_name"
                },
                {
                    'title':'邮箱',
                    "data": "email"
                },
                {
                    'title':'手机号',
                    "data": "phone"
                },
                {
                    'title':'来源',
                    "data": "source",
                    "render": function(data,type,row,meta){
                        if(data==1){
                            return '内部';
                        } else {
                            return '外部';
                        }
                    }
                },
                {
                    'title':'机构',
                    "data": "ogz_name"
                },
                {
                    'title':'角色',
                    "data": "roles_name"
                },
                {
                    "title":"操作",
                    "targets": -2,
                    "data": null,
                    "render": function(data,type,row,meta){
                        var button = m1.button('user');
                        var cur_user = {{\Auth::user()->id}};
                        var relation_button = '';
                        if(cur_user == row['id']){
                            if(row['attched']){
                                relation_button = button[7] + "&nbsp";
                            } else {
                                relation_button = button[6] + "&nbsp";

                            }
                        }
                        var _other = row['source'] == 0 ? button[4] + "&nbsp" + button[5] + "&nbsp" : relation_button;
                        if(row.id==1){
                            if(row.status===0){
                                return _other + button[0] + button[2];
                            }else{
                                return _other + button[0];
                            }
                        }else{
                            if(row.status == 0){
                                // button1 = button[2];
                                return button[2];
                            }else{

                                return _other + button[0] +"&nbsp"+ button[1];
                            }
                            // return _other + button[0] +"&nbsp"+ button1;
                        }
                    }
                }],
            //所有列过滤xss
            columnDefs:[{
                "targets": "_all",
                "render": $.fn.dataTable.render.text()
            }],

            initComplete: function () {
                var button = '<button class="btn btn-primary add-row user-add" style="float: left;">增加</button>';
                $('.dataTables_filter').html(button);
                var _$this = this;

                m1.filter(jQuery,true,_$this,false);
            }
        });
        //编辑赋值
        $('#example1 tbody').on( 'click', 'button#editrow', function () {
            var data = tables.row( $(this).parents('tr') ).data();
            var fields = $("#add-form").serializeArray();
            //Id
            var id = data['id'];
            //用户名禁止编辑readonly
            $(':input[name="name"]').attr('readOnly');
            //更新提交按钮
            $("#submit-data").attr('id','submit-data2');
            jQuery.each(fields, function(i, field){

                //jquery根据name属性查找
                $(":input[name='"+field.name+"']").val(data[field.name]);
            });
            editLayer = layer.open({
                    title:'编辑用户',
                    zIndex:10,
                    type:1,
                    content:$("#edit"),
                    cancel:function(){
                        $('#edit').hide();
                    },
                    success:function(){
                        //查询关联信息
                        $.ajax({
                            url:"{{route('admin.access.user.row')}}",
                            method:"GET",
                            data:{uid:id}
                        }).done(function(data){
                            getToken();
                            // var data = $.parseJSON(data);
                            if(data.code===0){
                                //输出checkbox
                                var roles = data.roles;
                                var html = '';
                                $.each(roles,function(k,v){
                                    html += '<input type="checkbox" name="roles[]" value="'+v.id+'" id="perm_'+v.id+'"';
                                    for(var i=0;i<data.userRoles.length;i++){
                                        if(v.id === data.userRoles[i].id){
                                            html += 'checked';
                                        }
                                    }
                                    html += ' /><label for="perm_'+v.id+'">'+v.name+'</label>';
                                });
                                $('#roles').html(html);
                                var userOgzs = typeof(data.userOgzs[0]) != "undefined" ? data.userOgzs[0]['id'] : '';
                                //select ogz
                                $('#parent-ogz').html(m1.eachSelect(data.ogzs,'ogz',userOgzs));
                                //select tree
                                $('#parent-ogz').select2ToTree({language:'zh-CN'});
                            }
                        }).fail(function(data){
                            layer.msg('网络异常');
                        });
                    },
                    area:['auto','550px'],
                    maxWidth:'800',
                    offset:['80px','400px']
                }
            );
        });
        //编辑提交
        $('#edit').on('click','button#submit-data2',function(){
            fields = $("#add-form").serializeArray();

            $.ajax(
                {
                    url:"{{route('admin.access.user.update')}}",
                    method:"POST",
                    headers:{'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')},
                    data:fields
                }
            ).done(function(data){
                if(data.code===0){
                    $("#edit").hide();
                    getToken();
                    layui.use('layer', function(){
                        var layer = layui.layer;

                        layer.msg('修改成功');
                        //关闭弹窗
                        layer.close(editLayer);
                        //刷新table跳转到首页
                        // tables.ajax.reload();
                        //刷新当前页
                        window.location.reload();
                    });
                }else{
                    layer.msg(data.msg);
                }
            }).fail(function(data){
                $.each(data.responseJSON, function (key, value) {
                    var input = '#add-form input[name=' + key + ']';
                    //$(input).css("border","1px solid red");
                    layer.msg(value[0]);
                    return false;
                });
            });
        });
        //删除记录
        $('#example1 tbody').on( 'click', 'button#delrow', function () {
            var data = tables.row($(this).parents('tr') ).data();
            m1.delete(jQuery,layer,"{{route('admin.access.user.delete')}}",data);
        });
        //启用
        $('#example1 tbody').on( 'click', 'button#activerow', function () {
            var data = tables.row($(this).parents('tr') ).data();
            m1.active(jQuery,layer,"{{route('admin.access.user.active')}}",data,tables);
        });
        //查看基础信息
        $('#example1 tbody').on( 'click', 'button.ext', function () {
            var data = tables.row($(this).parents('tr') ).data();
            var _where = {id:data['id']};
            var _header = $('meta[name="csrf-token"]').attr('content');
            var res = m1.ajax("{{route('admin.access.user.ext')}}",'get',_where,true,_header).then(function(response){
                var _cont = '<div class="box-body no-padding"><table class="table"><tbody>';
                if(response.code === 0){
                    var _sex = response.data[0].sex == 1 ? '男' : '女';
                    _cont += '<tr><td>别名：</td><td>'+ response.data[0].alias +'</td></tr>';
                    _cont += '<tr><td>性别：</td><td>'+ _sex +'</td></tr>';
                    _cont += '<tr><td>生日：</td><td>'+ response.data[0].birth +'</td></tr>';
                    _cont += '<tr><td>团队：</td><td>'+ response.data[0].team +'</td></tr>';
                    _cont += '<tr><td>微信：</td><td>'+ response.data[0].wechat +'</td></tr>';
                    _cont += '<tr><td>qq：</td><td>'+ response.data[0].qq +'</td></tr>';
                    _cont += '<tr><td>个人主页：</td><td>'+ response.data[0].home_page +'</td></tr>';
                } else {
                    _cont += '<tr><td>'+ response.msg +'</td></tr>';
                }
                _cont += '</tbody></table></div>';
                $(".user-base").html(_cont);
                layer.open({
                    title:'基础信息',
                    zIndex:10,
                    type:1,
                    area: '300px',
                    closeBtn:1,
                    shadeClose:true,
                    content:$(".user-base"),
                    end:function(){
                        $('.user-base').hide();
                    }
                });
            }, function(error) {
                layer.msg(error);
            });
            getToken();
        });
        //查看收货地址
        $('#example1 tbody').on( 'click', 'button.address', function () {
            _this = $(this);
            var data = tables.row($(this).parents('tr') ).data();
            var _where = {id:data['id']};
            m1.ajax("{{route('admin.access.user.address')}}",'GET',_where,true).then(function(response){
                var _address = '<div class="box-body no-padding"><table class="table"><tbody>';
                if(response.code === 0){
                    for(var i in response.data){
                        _address += '<tr><td>'+ response.data[i].user_name +'</td><td>'+ response.data[i].province + response.data[i].city  + response.data[i].area + response.data[i].street +'</td><td>'+ response.data[i].phone +'</td><td>';
                        if(response.data[i]['is_default']){
                            _address += '默认';
                        }
                        _address += '</td></tr>';
                    }
                } else {
                    _address += '<td><span>'+ response.msg +'</span></td>';
                }
                _address += '</tbody></table></div>';
                $(".user-address").html(_address);
                // var _offsetTop = _this.position().top;
                // var _offsetTop1 = _this.offset().top;
                layer.open({
                    title:'收货地址',
                    zIndex:10,
                    type:1,
                    area: '500px',
                    closeBtn:1,
                    shadeClose:true,
                    content:$(".user-address"),
                    end:function(){
                        $('.user-address').hide();
                    }
                });
            }, function(error) {
                layer.msg(error);
            });
            getToken();
        });
        //绑定外部用户
        $('#example1 tbody').on( 'click', 'button.attach-user', function () {
            var data = tables.row( $(this).parents('tr') ).data();
            //Id
            var id = data['id'];
            msgLayer(id,'绑定外部用户',"{{route('admin.access.user.attach')}}");
        });
        //解绑外部用户
        $('#example1 tbody').on( 'click', 'button.detach-user', function () {
            var data = tables.row( $(this).parents('tr') ).data();
            //Id
            var id = data['id'];
            msgLayer(id,'解绑外部用户',"{{route('admin.access.user.detach')}}");
        });
        //信息层
        function msgLayer (id,tit,uri) {
            layer.open(
                {
                    title:tit,
                    zIndex:10,
                    type:1,
                    content:$("#relation"),
                    end:function(){
                        $('#relation').hide();
                    },
                    success:function(){
                        //添加识别标签
                        var id_input = '<input name="id" type="hidden" value="'+ id +'"/>';
                        var uri_input = '<input name="uri" type="hidden" value="'+ uri + '"/>';
                        $('#relation').append(id_input+uri_input);
                    }
                }
            );
        }
        //提交服务器
        $('.user-relation').click(function(){
            var _header = $('meta[name="csrf-token"]').attr('content');
            var _data = $('#relation_form').serializeArray();
            var _req_data = {'id':_data[2]['value'],'name':_data[0]['value'],'pass':_data[1]['value']};
            var _req_uri = $('#relation_form input[name="uri"]').val();
            m1.ajax(_req_uri,'post',_req_data,true,_header).then(function(response){
                if(response.code === 0){
                    layer.msg('操作成功');
                    window.location.reload();
                } else {
                    layer.msg(response.msg);
                }
            }, function(error) {
                layer.msg(error);
            });
            getToken();
        });
        //添加页面
        $('.box-body').on('click','button.add-row',function(){
            //排序字段
            $('#sort-order').hide();
            //reset表单
            $("#add-form")[0].reset();
            //清除隐藏域的值
            $(':input[type="hidden"]').val('');
            //用户名去除readonly
            $(':input[name="name"]').removeAttr('readOnly');
            //更新提交按钮
            $("#submit-data2").attr('id','submit-data');
            //添加层
            addLayer = layer.open({
                title:'新增用户',
                zIndex:10,
                type:1,
                content:$("#edit"),
                end:function(){
                    $('#edit').hide();
                },
                success:function() {
                    //查询关联信息
                    $.ajax({
                        url:"{{route('admin.access.user.row')}}",
                        method:"GET",
                        data:{uid:0}
                    }).done(function(data){
                        getToken();
                        // var data = $.parseJSON(data);
                        if(data.code===0){
                            //输出checkbox
                            var roles = data.roles;
                            var html = '';
                            $.each(roles,function(k,v){
                                html += '<input type="checkbox" name="roles[]" value="'+v.id+'" id="perm_'+v.id+'"';
                                for(var i=0;i<data.userRoles.length;i++){
                                    if(v.id === data.userRoles[i].id){
                                        html += 'checked';
                                    }
                                }
                                html += ' /><label for="perm_'+v.id+'">'+v.name+'</label>';
                            });
                            $('#roles').html(html);
                            var userOgzs = typeof(data.userOgzs[0]) != "undefined" ? data.userOgzs[0]['id'] : '';
                            //select ogz
                            $('#parent-ogz').html(m1.eachSelect(data.ogzs,'ogz',userOgzs));
                            //select tree
                            $('#parent-ogz').select2ToTree({language:'zh-CN'});
                        }
                    }).fail(function(data){
                        layer.msg('网络异常');
                    });
                },
                area:['auto','550px'],
                maxWidth:'800',
                offset:['80px','400px']
            });
        });
        //新增
        $('#edit').on( 'click', 'button#submit-data', function () {
            var fields = $("#add-form").serializeArray();
            $.ajax(
                {
                    url:"{{route('admin.access.user.add')}}",
                    method:"POST",
                    data:fields,
                    headers:{'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')},
                }
            ).done(function(data){
                getToken();
                if(data.code===0){
                    //避免跳转出现浮框
                    $('#add').hide();
                    layer.close(layer.index);
                    //刷新table跳转到首页
                    // tables.ajax.reload();
                    //刷新当前页
                    window.location.reload();
                    layer.msg('操作成功');
                } else {
                    layer.msg(data.msg);
                }
            }).fail(function (data) {
                $.each(data.responseJSON, function (key, value) {
                    var input = '#add-form input[name=' + key + ']';
                    // $(input).css("border","1px solid red");
                    layer.msg(value[0]);
                    return false;
                });
            });
        });
    });
</script>
@endsection